package com.group.neps.controller;


import com.group.common.users.NEPSUser;
import com.group.common.users.Sex;
import com.group.common.utils.MyUtils;

import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.stage.Stage;

import java.util.ArrayList;
import java.util.HashMap;

import static com.group.common.users.Sex.*;

public class NepsRegisterViewController {
    @FXML
    private TextField txtPhoneNumber;
    @FXML
    private TextField txtUserName;
    @FXML
    private TextField txtRemark;
    @FXML
    private RadioButton rdoMale;
    @FXML
    private RadioButton rdoFemale;
    @FXML
    private PasswordField txtPassword;
    @FXML
    private PasswordField txtConfirm;
    @FXML
    private Button btnRegister;
    @FXML
    private Button btnCancel;

    private ToggleGroup genderGroup;
    private ArrayList<NEPSUser> userList;

    @FXML
    public void initialize() {
        //设置单选格
        genderGroup = new ToggleGroup();
        rdoMale.setToggleGroup(genderGroup);
        rdoFemale.setToggleGroup(genderGroup);
    }

    public void saveUser() {
        //获取用户输入的注册信息
        String phoneNumber = txtPhoneNumber.getText();
        String userName = txtUserName.getText();
        String remark = txtRemark.getText();
        String gender = ((RadioButton)genderGroup.getSelectedToggle()).getText();
        Sex sex;
        String password = txtPassword.getText();
        String rePassword = txtConfirm.getText();

        //获取用户选择的性别
        if(gender.equals("男")) {
            sex = MALE;
        }else if(gender.equals("女")) {
            sex = FEMALE;
        }else{
            sex = UNKNOWN;
        }

        //判断密码设置是否符合标准
        if (password.equals(rePassword)) {
            NEPSUser u1 = new NEPSUser(userName, password, phoneNumber, remark, sex);
            //读取已注册的用户数据，并判断待注册的手机号是否已经被注册
            userList = MyUtils.readFileToArrayList("group/data/neps_userdata_arraylist.dat");
            for (NEPSUser u : userList) {
                if (u.getPhoneNumber().equals(phoneNumber)) {
                    MyUtils.showAlert("用户注册",null, "注册失败，手机号已注册已存在", Alert.AlertType.INFORMATION);
                    return;
                }
            }
            userList.add(u1);
            MyUtils.writeArrayListToFile("group/data/neps_userdata_arraylist.dat", userList);
            MyUtils.showAlert("用户注册",null, "注册成功", Alert.AlertType.INFORMATION);
        } else {
            MyUtils.showAlert("用户注册",null, "注册失败，密码不一致", Alert.AlertType.INFORMATION);
        }
        //跳转到登录界面
        MyUtils.showView((Stage)btnRegister.getScene().getWindow(),"group/neps/view/NepsLoginView.fxml");
    }

    public void cancel() {
        //返回到初始登录界面
        MyUtils.showView((Stage)btnCancel.getScene().getWindow(),"group/neps/view/NepsLoginView.fxml");
    }
}
